﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Common.Logging;

namespace MailCrawler.Workflow
{
	public static class EmailFetcher
	{
        private static readonly ILog Log = LogManager.GetCurrentClassLogger();

        static EmailFetcher()
        {
            var strs = File.ReadAllLines("Emails.txt");
            foreach (var s in strs)
                try
                {
                    var par = s.Split(' ');
                    var email = new EMail
                                    {
                                        MailType = (MailType) Enum.Parse(typeof (MailType), par[0]),
                                        Server = par[1],
                                        Port = System.Convert.ToInt32(par[2]),
                                        IsSSL = System.Convert.ToBoolean(par[3]),
                                        Login = par[4],
                                        Password = par[5]
                                    };
                    EMails.Add(email);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            if(EMails.Count==0)
                throw new InvalidDataException("There are no EMails to check");
            Log.Debug("Found "+EMails.Count+" emails to use;");
        }

	    public static List<EMail> EMails=new List<EMail>();

        public static int CurrentEmail { get; set; }

        public static EMail GetEMail()
        {
            if (!(CurrentEmail < EMails.Count))
                CurrentEmail = 0;
            var v= EMails[CurrentEmail++];
            return v;
        }
        public static void Save()
        {
            var v = from a in EMails 
                    select 
                    string.Format("{0} {1} {2} {3} {4} {5}",
                        a.MailType,
                        a.Server,
                        a.Port,
                        a.IsSSL,
                        a.Login,
                        a.Password
                        );
            File.WriteAllLines("Emails.txt", v.ToArray());
        }
	}
    public class EMail
    {
        public MailType MailType { get; set; }
        public string Server { get; set; }
        public int Port { get; set; }
        public bool IsSSL { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
        
    }
    public enum MailType
    {
        //IMAP,
        POP3
    }
}
